<template>
  <!-- 流程定义 -->
  <div>
    <el-row>
      <el-col style="margin-right: 10px" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <template>
              <el-button type="normal" @click="approve('approve')"
                >审批</el-button
              >
              <el-button type="normal" @click="approve('process')"
                >流程进度</el-button
              >
              <el-button type="normal" @click="reassignment()">改派</el-button>
              <el-button type="normal" @click="approve('approves')"
                >批量审批</el-button
              >
            </template>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    ref="searchForm"
                    :model="searchForm"
                    label-width="90px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="任务名称：">
                      <el-input
                        v-model="searchForm.taskDefName"
                        style="width: 180px"
                      />
                    </el-form-item>
                    <el-form-item label="流程名称：">
                      <el-input
                        v-model="searchForm.processDefName"
                        style="width: 180px"
                      />
                    </el-form-item>

                    <el-form-item label="接收时间">
                      <el-date-picker
                        v-model="searchForm.createdTmBegin"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        style="width: 180px"
                      />
                    </el-form-item>
                    <el-form-item label="至">
                      <el-date-picker
                        v-model="searchForm.createdTmEnd"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        style="width: 180px"
                      />
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(searchForm.page = 1), searchFunc()"
                      >查询</el-button
                    >
                    <el-button size="mini" @click="searchClear">重置</el-button>
                  </div>
                </div>
                <i slot="reference" class="iconfont icon-sousuo" title="搜索" />
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :key="item.prop"
                      :label="item.label"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  slot="reference"
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                />
              </el-popover>
            </div>
          </el-col>
        </el-row>

        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column width="55" type="selection"  />
          <el-table-column
            v-if="columnState[0]"
            prop="taskDefName"
            label="任务名称 "
            show-overflow-tooltip
          />

          <el-table-column
            v-if="columnState[1]"
            prop="processDefName"
            label="流程名称"
            show-overflow-tooltip
          />

          <el-table-column
            v-if="columnState[3]"
            prop="createdTm"
            label="接收时间"
            sortable
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnState[4]"
            prop="processInstanceUserName"
            label="流程发起人"
            sortable
            :formatter="(row) => row.processInstanceUserName || '-'"
          />

          <el-table-column
            v-if="columnState[5]"
            prop="taskApprover"
            label="待审批人"
            sortable
            :formatter="(row) => row.taskApprover || '-'"
          />
        </el-table>
        <pagination
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @refresh="searchFunc"
        />
      </el-col>
    </el-row>
    <!-- 审批弹框 -->
    <el-dialog
      v-dialogDrag
      title="任务审批"
      :visible.sync="taskVisible"
      width="50%"
    >
      <commonTab
        ref="commonTab"
        :businessKey="businessKey"
        :processInstanceId="processInstanceId"
        :save-titles="saveTitles"
        @buttonSign="buttonSign"
      />
      <div v-if="buttonShow" slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="taskVisible = false">取 消</el-button>
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button @click="taskVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!--改派弹框 -->
    <el-dialog
      v-dialogDrag
      title="改派"
      :visible.sync="reassignmentVisible"
      width="50%"
    >
      <reassignmentTable
        ref="reassignmentTable"
        @reassignClose="reassignClose"
        @approvered="approvered"
      />
    </el-dialog>
    <!--改派弹框 -->
  </div>
</template>
<script>
import commonTab from "@/views/workFlow/components/commonTab";
import reassignmentTable from "@/views/workFlow/components/reassignmentTable";
import { workflow } from "@/api/index";
import moment from "moment";
export default {
  components: {
    reassignmentTable,
    commonTab,
  },
  data() {
    return {
      buttonShow: true,
      businessKey: "",
      processInstanceId: "",
      row: [],
      approverVisible: false,
      reassignmentVisible: false,
      saveTitles: {
        list: [
          {
            title: "任务审批",
            show: false,
          },
          {
            title: "审批历史",
            show: true,
          },
          {
            title: "流程进度图",
            show: true,
          },
          {
            title: "业务表单",
            show: false,
          },
        ],
        activeName: "second",
      },
      taskVisible: false, // 审批等组件弹窗
      searchForm: {
        processDefCode: "",
        processDefName: "",
        taskDefName: "",
        page: 1,
        size: 15,
      },
      total: 0,
      saveForm: {
        processDefName: "",
        taskDefName: "",
        forward: "",
        // isSignTask: "", // 是否会签
        resultFlag: "",
        taskComment: "",
        taskIds: "",
        userNameString: "",
      },
      saveFormRules: {
        resultFlag: [
          { required: true, message: "请选择审批意见", trigger: "blur" },
        ],
        forward: [{ required: true, message: "请选择节点", trigger: "blur" }],
        userNameString: [
          { required: true, message: "请选择审批人", trigger: "blur" },
        ],
        taskComment: [{ validator: this.taskCommentVaild, trigger: "blur" }],
      },
      checkList: [],
      // 列隐藏
      textData: [
        { label: "任务名称" },
        { label: "流程名称" },
        { label: "接收时间" },
        { label: "流程发起人" },
        { label: "待审批人" },
      ],
      // 获取table的数据
      tableData: [],
      // 编辑行内数据暂存，供判断表单状态
      editRow: {},
      resultFlagList: [
        {
          value: "1",
          label: "通过",
        },
        {
          value: "0",
          label: "驳回",
        },
      ],
    };
  },
  computed: {
    columnState() {
      const arr = [];
      const arr1 = this.textData;
      const arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
  },
  watch: {
    taskVisible() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  created() {
    this.checkListInit();
    this.searchFunc();
  },
  mounted() {},
  methods: {
    buttonSign(val) {
      if (val === "first") {
        this.buttonShow = true;
      } else {
        this.buttonShow = false;
      }
    },
    taskCommentVaild(rule, value, callback) {
      if (this.saveForm.resultFlag === "0") {
        if (value === "") {
          callback(new Error("当审批意见为驳回时，备注不能为空"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 修改审批意见
    changeResultFlag(val) {
      this.saveForm.taskComment = "";
      this.saveForm.userName = [];
      this.saveForm.userNameString = "";
      this.saveForm.forward = "";
    },
    // 点击评审按钮
    approverBtn() {
      this.approverVisible = true;
    },
    // 获取用户列表
    showAddresseeList() {
      if (!this.saveForm.forward) {
        this.$message.warning("请先选择流转节点");
        return;
      }
      this.approverVisible = true;
      setTimeout(() => {
        this.$refs.approverTable.init(this.row[0], this.saveForm.forward);
      }, 30);
    },
    // 改派关闭
    reassignClose() {
      this.reassignmentVisible = false;
    },
    approverEvent(val) {
      this.approverVisible = false;
      const arr = val.map((v) => v.userName);
      this.saveForm.userName = arr;
      this.saveForm.userNameString = this.saveForm.userName.toString();
    },
    // 改派
    approvered(val) {
      // 任务改派
      const data = {
        taskId: this.row[0].taskInstanceId,
        userName: val.userName,
      };
      workflow.taskDelegate(data).then((res) => {
        if (res.code === 200) {
          this.$message.success("成功");
          this.reassignmentVisible = false;
          this.searchFunc();
        } else {
          this.$message.error(res.message || "失败");
        }
      });
    },
    searchClear() {
      for (const key in this.searchForm) {
        this.searchForm[key] = "";
      }
      this.searchForm.page = 1;
      this.searchForm.size = 15;
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchFunc() {
      const data = this.searchForm;
      workflow.queryForPageTaskInstance(data).then((res) => {
        this.tableData = res.datas.rows;
        this.total = res.datas.total;
      });
    },
    // 任务审批
    approve(type) {
      const selection = this.$refs.multipleTable.selection;
      this.row = this.$refs.multipleTable.selection;
      if (type === "approve" || type === "process") {
        if (selection.length !== 1) {
          return this.$message.warning("请选择一条数据");
        }
      }
      if (type === "approves") {
        if (selection.length < 1) {
          return this.$message.warning("请选择数据");
        }
        if (this.row.length > 1) {
          for (let i = 0; i < this.row.length - 1; i++) {
            for (let j = 0; j < this.row.length; j++) {
              if (
                this.row[i].processDefCode !== this.row[j].processDefCode ||
                this.row[i].taskDefCode !== this.row[j].taskDefCode
              ) {
                return this.$message.warning(
                  "	请选择相同的待审批任务进行批量审批！"
                );
              }
            }
          }
        }
      }
      if (type === "approve" || type === "approves") {
        this.saveTitles = {
          list: [
            {
              title: "任务审批",
              show: true,
            },
            {
              title: "审批历史",
              show: true,
            },
            {
              title: "流程进度图",
              show: true,
            },
            {
              title: "业务表单",
              show: true,
            },
          ],
          activeName: "first",
        };
      } else {
        this.saveTitles = {
          list: [
            {
              title: "任务审批",
              show: false,
            },
            {
              title: "审批历史",
              show: true,
            },
            {
              title: "流程进度图",
              show: true,
            },
            {
              title: "业务表单",
              show: false,
            },
          ],
          activeName: "second",
        };
      }
      this.businessKey = selection[0].businessKey;
      this.processInstanceId = selection[0].processInstanceId;
      this.taskVisible = true;
      setTimeout(() => {
        this.$refs.commonTab.init();
      }, 30);
    },
    // 点击改派
    reassignment() {
      const selection = this.$refs.multipleTable.selection;
      if (selection.length !== 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.row = this.$refs.multipleTable.selection
      this.reassignmentVisible = true;
      setTimeout(() => {
        this.$refs.reassignmentTable.init(selection[0]);
        this.$refs.reassignmentTable.getOrgList();
      }, 30);
    },
    saveFunc() {
      this.$refs.commonTab.$refs["saveForm"].validate((valid) => {
        if (valid) {
          const taskIds = this.row.map((v) => v.taskInstanceId);
          const data = {
            forward: this.$refs.commonTab.saveForm.forward, // 流转节点
            //  isSignTask: this.saveForm.isSignTask,
            taskComment: this.$refs.commonTab.saveForm.taskComment, // 备注
            taskIds: taskIds,
            // userName: this.$refs.commonTab.saveForm.userName, // 审批人
            resultFlag: this.$refs.commonTab.saveForm.resultFlag, // 同意驳回
          };
          workflow.approveDo(data).then((res) => {
            if (res.code === 200) {
              this.$message.success("成功");
              this.taskVisible = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "失败");
            }
          });
        }
      });
    },
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
